//
//  flvlist.js
//  firefox
//  
//  Created by Zak on 2008-06-12.
//  Copyright 2008 Ant.com. All rights reserved.
// 

top.AntFlvList =
{
    listBox: $('antFlvListBox'),
	flvLinks: new AntArray(),
    
    /**
     * Push a link in the global this.flvLinks and add it to the UI
     * @param flvLink       The flvLink Object containg data for this link
     * @return flvLink
     */
    push: function (flvLink)
    {
		var cmp = function (a, b) { return a.name == b.name; };

		flvLink.name = flvLink.name.sanitize();
		while (this.flvLinks.inArray(flvLink, cmp))
		{
			flvLink.incrementFlvName();
		}
		if (!this.flvLinks.inArray(flvLink, this.flvLinkCompare))
		{
			AntFlvUi.appendItem(flvLink, this.flvLinks.length);
	        this.flvLinks.push(flvLink)
			if (!AntFlvUi.isShown() && AntPrefs.getAntBranch().getBoolPref("notification"))
				this.notify(flvLink);
		}
		return flvLink;
    },

	/**
	 * Display the notification popup box
	 * @param flvLink       A flvLink object
	 */
	notify: function (flvLink)
	{
		var listener = 
		{
			observe: function(subject, topic, data) 
			{
				if (topic == "alertclickcallback")
					AntFlvList.download(flvLink);
			}
		};
		try 
		{
		    var title = AntLang.getFormatString("AntFlvList.NotificationTitle", flvLink.origin);
    		var text = AntLang.getFormatString("AntFlvList.NotificationText", flvLink.name);
    		var alertsService = CCSV("@mozilla.org/alerts-service;1", "nsIAlertsService");

    		alertsService.showAlertNotification("chrome://antbar/skin/logo.png", title, text, true, flvLink, listener);
		}
		catch (e)
		{
            // AntLib.toLog("Cannot notify flvLInk = " + inspect(flvLink) + " ex = " + e);
		}
	},

	/**
	 * Set a node of listBox downloaded
	 */
	setDownloadedNode: function (node, path)
	{
		node.style.backgroundColor = "#CCE6FF";
		node.style.color = "#000000";
		node.downloaded = true;
		node.path = path;
	},

	/**
	 * Is downloaded node
	 * @param node
	 */
	isDownloadedNode: function (node)
	{
		return node.downloaded;
	},

	/**
	 * Set a node of listBox as previously downloaded
	 */
	setPrevDownloadedNode: function (node)
	{
		node.style.backgroundColor = "#CCCCCC";
	},

	/**
	 * Download a file
	 * @param if true the Firefox download manager won't be opened
	 */
	download: function (flvLink, doNotOpen)
	{
		var node = AntFlvUi.getItemByUrl(flvLink.url);
		var path = AntDownloadManager.downloadFlv(flvLink, doNotOpen);

		if (path)
		{
			this.setDownloadedNode(node, path);
			return true;
		}
		this.setPrevDownloadedNode(node);
		
		return false;
	},
	
	/**
	 * getFlvLinkByUrl: return the flvLink object matching the url
	 * @param url to match
	 */
	getFlvLinkByUrl: function (url)
	{
		for (var i = 0; i < this.flvLinks.length; i++)
			if (this.flvLinkCompare(this.flvLinks[i], {url: url}))
				return this.flvLinks[i];

		return null;
	},

	/*
	 * Simple compare function for AntFlvLink objects
	 * @return              true if a and b are equal, false if not
	 */
	 flvLinkCompare: function (a, b)
	 {
		return a.url == b.url;
	 },
    
    /**
     * Drop the global this.flvLinks and regenerate the UI list
     */
    clean: function ()
    {
        this.flvLinks = new AntArray();
        this.refreshDisplay();
    },
    
    /**
     * Regenerate the UI list (drop and append loop)
     */
    refreshDisplay: function ()
    {
        AntFlvUi.removeAll();
        for (var i = 0; i < this.flvLinks.length; i++)
        {
            if (this.flvLinks[link].origin && this.flvLinks[link].url && this.flvLinks[link].name)
                AntFlvUi.appendItem(this.flvLinks[link].origin, this.flvLinks[link].url, this.flvLinks[link].name, i);
        }
    },
    
    /**
     * Callback: fired when an item is double clicked on the list
     */
    onItemSelected: function (event)
    {
        var nodes = event.target.childNodes;
        var url = nodes[1].getAttribute('label');
		var flvlink = this.getFlvLinkByUrl(url);
		
		if (event.target.path)
		{
			AntPrefs.flvToPlay(event.target.path);
			AntBar.onPlayerButtonClick(null);
		}
		else if (flvlink)
			this.download(flvlink);
    },
    
    /**
     * Callback: fired from the context menu "Download current"
     */
    onPopupDownloadCurrent: function (event)
    {
        var url = document.popupNode.childNodes[1].getAttribute('label');
		var flvlink = this.getFlvLinkByUrl(url);

		if (flvlink)
	      this.download(flvlink);
    },
    
    /**
     * Callback: fired from the context menu "Copy movie location"
     */
    onPopupCopyMovieLocation: function (event)
    {
        clipboardHelper.copyString(document.popupNode.childNodes[1].getAttribute('label'));
    },
    
    /**
     * Callback: fired from the context menu "Rename"
     */
    onPopupRename: function (event)
    {
        var url = document.popupNode.childNodes[1].getAttribute('label');
        var name = document.popupNode.childNodes[2].getAttribute('label');
		var flvlink = this.getFlvLinkByUrl(url);

		name = name.replace(/_/g,' ');
		var newName = prompt(AntLang.getFormatString("AntFlvList.PromptRenameText", name), name);

		if (!newName)
			return;

		if (!newName.match(/^[\w -]+$/i))
		{
			alert(AntLang.getString("AntFlvList.InvalidFileName"));
			return ;
		}
		if (flvlink)
		{
	        flvlink.name = newName.replace(/[ ]/g,'_');
			document.popupNode.childNodes[2].setAttribute('label', newName);
		}

    },

    /**
     * Callback: fired from the context menu "Download selected"
     */
    onPopupDownloadSelected: function (event)
    {    
        var lines = $('antFlvListBox').selectedItems;
        
        for (var i = 0; i < lines.length; i++)
        {
            var nodes = lines[i].childNodes;
            var url = nodes[1].getAttribute('label');
			var flvlink = this.getFlvLinkByUrl(url);

			if (flvlink)
			{
				this.download(flvlink, (i != lines.length - 1));
			}
        }
    },
    
    /**
     * Callback: fired from the context menu "Download all"
     */
    onPopupDownloadAll: function (event)
    {
		if (!confirm(AntLang.getFormatString("AntFlvList.ConfirmDownload")))
			return ;

        for (var i = 0; i < this.flvLinks.length; i++)
        {
            this.download(this.flvLinks[i], (i != this.flvLinks.length - 1));
        }
    },
    
    /**
     * Callback: fired from the context menu "Clean movies list"
     */
    onPopupClearList: function ()
    {
	    this.clean();
    },

	/**
	 * Callback when opening the popup menu, used in order to display or not the "Play Now" option
	 */
	onPopupShowing: function ()
	{
        var url = document.popupNode.childNodes[1].getAttribute('label');
		var node = AntFlvUi.getItemByUrl(url);

		if (this.isDownloadedNode(node))
			$("antFlvListPopupPlayCurrent").setAttribute("hidden", false);
		else
			$("antFlvListPopupPlayCurrent").setAttribute("hidden", true);
	},

	/**
	 * Play the currently selectd video in the player,
	 * only available when the movies has already been added to the download queue
	 */
	onPopupPlayCurrent: function ()
	{
        var url = document.popupNode.childNodes[1].getAttribute('label');
		var node = AntFlvUi.getItemByUrl(url);

		if (node.path)
		{
			AntPrefs.flvToPlay(node.path);
			AntBar.onPlayerButtonClick(null);
		}
	},
}
